//
//  ViewController.m
//  UI27_音乐播放器
//
//  Created by dllo on 16/8/20.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "YH_Lrc.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate, AVAudioPlayerDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UISlider *progressSlider;
@property (strong, nonatomic) IBOutlet UISlider *voiceSlider;
@property (strong, nonatomic) IBOutlet UILabel *currentLabel;
@property (strong, nonatomic) IBOutlet UILabel *lastLabel;

@property (strong, nonatomic) IBOutlet UIButton *playButton;

@property (nonatomic, strong) NSArray *lrcArray;
@property (nonatomic, strong) NSArray *musicArray;
@property (nonatomic,assign) NSInteger mp3Index;
@property (nonatomic,assign) NSUInteger currentRow;

@property (nonatomic, strong) NSTimer *timer;

// 本地
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) YH_Lrc *yh_lrc;

@end

@implementation ViewController





- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self createData];
    [self createTableView];
//    [self.progressSlider addTarget:self action:@selector(sliderProgressAction:) forControlEvents:UIControlEventValueChanged];
    }
//- (void)sliderProgressAction:(UISlider *)slider {
//    if (slider.state == UIGestureRecognizerStateBegan) {
//        [self.audioPlayer stop];
//        self.audioPlayer.currentTime = slider.value;
//    } else if (slider.state == UIGestureRecognizerStateEnded) {
//        [self.audioPlayer play];
//    }
//}

- (void)createData {
    self.lrcArray = [NSArray array];
    self.lrcArray = @[[[NSBundle mainBundle] pathForResource:@"薛之谦-初学者" ofType:@".lrc"], [[NSBundle mainBundle] pathForResource:@"薛之谦-演员" ofType:@".lrc"]];
    
    self.musicArray = [NSArray array];
    self.musicArray = @[[[NSBundle mainBundle] pathForResource:@"薛之谦-初学者" ofType:@".mp3"], [[NSBundle mainBundle] pathForResource:@"薛之谦-演员" ofType:@".mp3"]];
    
    self.yh_lrc = [[YH_Lrc alloc] init];
    [self loadMP3:self.musicArray[self.mp3Index] lrcPath:self.lrcArray[self.mp3Index]];
    
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];
}


- (void)changeTime:(NSTimer *)timer {
    // 让歌词随着progressSlider变化
    self.progressSlider.value = self.audioPlayer.currentTime;
    NSString *str = [self.yh_lrc.timeArray lastObject];
    NSArray *lastTimeArray = [str componentsSeparatedByString:@":"];
    NSString *str1 = [lastTimeArray[0] stringByAppendingString:@":"];
    NSString *str3 = [lastTimeArray[1] substringToIndex:2];
    NSString *str2 = [str1 stringByAppendingString:str3];
    self.lastLabel.text = str2;
    
    [self.yh_lrc.timeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *timeStr = self.yh_lrc.timeArray[idx];
        NSArray *timeArray = [timeStr componentsSeparatedByString:@":"];
        CGFloat seconds = [timeArray[0] floatValue] * 60 + [timeArray[1] floatValue];
        NSString *str1 = [timeArray[0] stringByAppendingString:@":"];
        NSString *str = [timeArray[1] substringToIndex:2];
        NSString *str2 = [str1 stringByAppendingString:str];
        self.currentLabel.text = str2;
        if (seconds >= self.audioPlayer.currentTime) {
            if (idx == 0) {
                self.currentRow = idx;
            } else {
                self.currentRow = idx - 1;
            }
            *stop = YES;
        }
    }];
    [self.tableView reloadData];
    if (self.currentRow < self.yh_lrc.lrcArray.count) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
}

- (void)loadMP3:(NSString *)MP3Str lrcPath:(NSString *)lrcStr {
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:MP3Str] error:nil];
    self.audioPlayer.delegate = self;
    self.audioPlayer.volume = 0.5f;
    [self.yh_lrc lrcWithFileURL:lrcStr];
    
    self.progressSlider.maximumValue = self.audioPlayer.duration;
    [self.audioPlayer prepareToPlay];
}
// 播放或者暂停
- (IBAction)playButton:(id)sender {
    if (self.audioPlayer.playing) {
        [self.playButton setImage:[UIImage imageNamed:@"hp_player_btn_play_normal"] forState:UIControlStateNormal];
        [self.audioPlayer pause];
    } else {
        [self.playButton setImage:[UIImage imageNamed:@"hp_player_btn_pause_normal"] forState:UIControlStateNormal];
        [self.audioPlayer play];
    }
}
// 下一曲
- (IBAction)nextButton:(id)sender {
     [self.playButton setImage:[UIImage imageNamed:@"hp_player_btn_pause_normal"] forState:UIControlStateNormal];
    [self.audioPlayer stop];
    self.mp3Index++;
    if (self.mp3Index == 2) {
        self.mp3Index = 0;
    }
    [self loadMP3:self.musicArray[self.mp3Index] lrcPath:self.lrcArray[self.mp3Index]];
    [self.audioPlayer play];
}
// 上一曲
- (IBAction)lastButton:(id)sender {
     [self.playButton setImage:[UIImage imageNamed:@"hp_player_btn_pause_normal"] forState:UIControlStateNormal];
    [self.audioPlayer stop];
    self.mp3Index--;
    if (self.mp3Index == -1) {
        self.mp3Index = 1;
    }
    [self loadMP3:self.musicArray[self.mp3Index] lrcPath:self.lrcArray[self.mp3Index]];
    [self.audioPlayer play];
}
// 控制进度条
- (IBAction)changeProgress:(UISlider *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {
        self.audioPlayer.currentTime = sender.value;
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        [self.audioPlayer play];
    }
}


// 控制声音
- (IBAction)changeVoice:(UISlider *)sender {
    self.audioPlayer.volume = sender.value;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [self nextButton:nil];
}

- (void)createTableView {
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 60;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.yh_lrc.lrcArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    if (indexPath.row < self.yh_lrc.lrcArray.count) {
        cell.textLabel.text = self.yh_lrc.lrcArray[indexPath.row];
    }
    cell.textLabel.textAlignment = 1;
    cell.textLabel.numberOfLines = 0;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    if (self.currentRow == indexPath.row) {
        cell.textLabel.textColor = [UIColor redColor];
    } else {
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    
    return cell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
